﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;

namespace FlowersStore
{
    public partial class AdminProductDetails : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && cblCategories != null)
            {
                if (Request.UrlReferrer != null)
                    ViewState["PreviousPageUrl"] = Request.UrlReferrer.ToString();
                if (cblCategories != null)
                    cblCategories.DataBind();
                if (Request.QueryString["product"] != null)
                {
                    TryFillFields();
                    btnOk.Text = "Изменить";
                }
                else
                    btnOk.Text = "Добавить";
            }
        }

        private void TryFillFields()
        {
            int product;
            if (!int.TryParse(Request.QueryString["product"].ToString(), out product))
            {
                Response.Redirect("AdminProducts.aspx");
                return;
            }
            using (FlowerStoreDataContext db = new FlowerStoreDataContext())
            {
                Product pr = (from p in db.Products
                              where p.Product_id == product
                              select p).SingleOrDefault();
                if (pr == null)
                {
                    Response.Redirect("AdminProducts.aspx");
                    return;
                }
                FillFields(product);
            }
        }

        private void FillFields(int product)
        {
            FlowerStoreDataContext db = new FlowerStoreDataContext();
            Product prod = (from p in db.Products
                            where p.Product_id == product
                            select p).Single();
            tbName.Text = prod.Product_name;
            tbArticle.Text = prod.Product_article;
            tbDescription.Text = prod.Product_description;
            imgBig.ImageUrl = prod.Product_imgUrl;
            imgThumb.ImageUrl = prod.Product_thimbnailUrl;
            tbPrice.Text = prod.Product_price.ToString();
            var categories = db.GetCategoriesForProduct(product);
            foreach (var cat in categories)
            {
                var item = cblCategories.Items.FindByValue(cat.Category_id.ToString());
                item.Selected = (cat.belongs == 1);
            }
            btnOk.Text = "Изменить";
        }

        protected void btnLoadBig_Click(object sender, EventArgs e)
        {
            if (uploadBig.HasFile)
            {
                try
                {
                    string ext = Path.GetExtension(uploadBig.PostedFile.FileName);
                    if (ext == ".jpg" || ext == ".png")
                    {
                        string fileName = Server.MapPath("./ProductImages/Big/") + uploadBig.PostedFile.FileName;
                        string location = fileName;
                        uploadBig.SaveAs(location);
                        ResizeBitmap(location, new Size(465, 545));

                        imgBig.ImageUrl = "ProductImages/Big/" + uploadBig.PostedFile.FileName;
                        lblBigStatus.Text = uploadBig.PostedFile.FileName;
                    }
                    else
                    {
                        imgBig.ImageUrl = "";
                        lblBigStatus.Text = "Укажите файл изображения (*.jpg; *.png)";
                    }
                }
                catch (Exception)
                {
                    lblBigStatus.Text = "Не удалось загрузить изображение";
                }
            }
            else
            {
                imgBig.ImageUrl = "";
                lblBigStatus.Text = "";
            }
        }

        protected void btnUploadThumb_Click(object sender, EventArgs e)
        {
            if (uploadThumb.HasFile)
            {
                try
                {
                    string ext = Path.GetExtension(uploadThumb.PostedFile.FileName);
                    if (ext == ".jpg" || ext == ".png")
                    {
                        string fileName = Server.MapPath("./ProductImages/Thumbs/") + uploadThumb.PostedFile.FileName;
                        string location = fileName;
                        uploadThumb.SaveAs(location);
                        ResizeBitmap(location, new Size(175, 205));
                        imgThumb.ImageUrl = "ProductImages/Thumbs/" + uploadThumb.PostedFile.FileName;
                        lblThumbStatus.Text = uploadThumb.PostedFile.FileName;
                    }
                    else
                    {
                        imgThumb.ImageUrl = "";
                        lblThumbStatus.Text = "Укажите файл изображения (*.jpg; *.png)";
                    }
                }
                catch
                {
                    lblThumbStatus.Text = "Не удалось загрузить изображение";
                }
            }
            else
            {
                imgThumb.ImageUrl = "";
                lblThumbStatus.Text = "";
            }
        }

        void ResizeBitmap(string path, Size size)
        {
            System.Drawing.Image srcBmp = System.Drawing.Image.FromFile(path);
            int sourceWidth = srcBmp.Width;
            int sourceHeight = srcBmp.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)size.Width / (float)sourceWidth);
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;
            if (nPercent > 1)
                return;
            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap destBmp = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage(destBmp);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            g.DrawImage(srcBmp, 0, 0, destWidth, destHeight);
            g.Dispose();
            srcBmp.Dispose();
            destBmp.Save(path);

        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            if (ViewState["PreviousPageUrl"] != null)
                Response.Redirect(ViewState["PreviousPageUrl"].ToString());
            //Response.Redirect(Request.UrlReferrer.AbsolutePath);
        }

        protected void btnOk_Click(object sender, EventArgs e)
        {
            int productId;
            using (FlowerStoreDataContext db = new FlowerStoreDataContext())
                if (Request.QueryString["product"] != null)
                {
                    if (int.TryParse(Request.QueryString["product"], out productId))
                    {
                        var product = (from p in db.Products
                                       where p.Product_id == productId
                                       select p).SingleOrDefault();
                        if (product == null)
                            return;
                        product.Product_name = tbName.Text;
                        product.Product_description = tbDescription.Text;
                        product.Product_article = tbArticle.Text;
                        product.Product_price = decimal.Parse(tbPrice.Text);
                        if (imgBig.ImageUrl != "")
                            product.Product_imgUrl = imgBig.ImageUrl;
                        if (imgThumb.ImageUrl != "")
                            product.Product_thimbnailUrl = imgThumb.ImageUrl;

                        foreach (ListItem item in cblCategories.Items)
                            if (!item.Selected)
                            {
                                int catId = int.Parse(item.Value);
                                var prodCat = (from pc in db.CategoryProductM2Ms
                                               where pc.Category_id == catId && pc.Product_id == product.Product_id
                                               select pc).SingleOrDefault();
                                if (prodCat != null)
                                    db.CategoryProductM2Ms.DeleteOnSubmit(prodCat);
                            }
                            else
                            {
                                int catId = int.Parse(item.Value);
                                var prodCat = (from pc in db.CategoryProductM2Ms
                                               where pc.Category_id == catId && pc.Product_id == product.Product_id
                                               select pc).SingleOrDefault();
                                if (prodCat == null)
                                {
                                    prodCat = new CategoryProductM2M();
                                    prodCat.Product_id = product.Product_id;
                                    prodCat.Category_id = catId;
                                    db.CategoryProductM2Ms.InsertOnSubmit(prodCat);
                                }
                            }
                        db.SubmitChanges();
                    }
                }
                else
                {
                    Product product = new Product();
                    product.Product_name = tbName.Text;
                    product.Product_description = tbDescription.Text;
                    product.Product_article = tbArticle.Text;
                    product.Product_price = decimal.Parse(tbPrice.Text);
                    if (imgBig.ImageUrl != "")
                        product.Product_imgUrl = imgBig.ImageUrl;
                    if (imgThumb.ImageUrl != "")
                        product.Product_thimbnailUrl = imgThumb.ImageUrl;

                    db.Products.InsertOnSubmit(product);
                    db.SubmitChanges();

                    foreach (ListItem item in cblCategories.Items)
                        if (item.Selected)
                        {
                            int catId = int.Parse(item.Value);
                            var prodCat = (from pc in db.CategoryProductM2Ms
                                           where pc.Category_id == catId && pc.Product_id == product.Product_id
                                           select pc).SingleOrDefault();
                            if (prodCat == null)
                            {
                                prodCat = new CategoryProductM2M();
                                prodCat.Product_id = product.Product_id;
                                prodCat.Category_id = catId;
                                db.CategoryProductM2Ms.InsertOnSubmit(prodCat);
                            }
                        }
                    db.SubmitChanges();
                }
            if (ViewState["PreviousPageUrl"] != null)
                Response.Redirect(ViewState["PreviousPageUrl"].ToString());
        }

        protected void ValidateText(object sender, EventArgs e)
        {
            UniqueArticleValidator.Validate();
        }

        protected void ValidateArticle(object source, ServerValidateEventArgs args)
        {
            using (FlowerStoreDataContext db = new FlowerStoreDataContext())
            {
                var prod = (from p in db.Products
                            where p.Product_article == args.Value
                            select p).SingleOrDefault();
                args.IsValid = (prod == null);
            }
        }
    }

}